// 全局变量
let audioFiles = [];
let currentSongIndex = -1;
let lyrics = [];
let audioElement = new Audio();
let isPlaying = false;
let updateInterval;
let fileSelector;
let sidebar;
let mainContent;
let songList;
let lyricsContainer;
let progressBar;
let currentTimeDisplay;
let durationDisplay;
let folderInput;
let selectFolderBtn;
let playPauseBtn;
let prevBtn;
let nextBtn;
let volumeControl;


function onLoad() {
    // DOM元素
    fileSelector = document.getElementById('fileSelector');
    sidebar = document.getElementById('sidebar');
    mainContent = document.getElementById('mainContent');
    songList = document.getElementById('songList');
    lyricsContainer = document.getElementById('lyricsContainer');
    progressBar = document.getElementById('progressBar');
    currentTimeDisplay = document.getElementById('currentTime');
    durationDisplay = document.getElementById('duration');
    folderInput = document.getElementById('folderInput');
    selectFolderBtn = document.getElementById('selectFolderBtn');
    playPauseBtn = document.getElementById('playPauseBtn');
    prevBtn = document.getElementById('prevBtn');
    nextBtn = document.getElementById('nextBtn');
    volumeControl = document.getElementById('volumeControl');

    // 事件监听器
    selectFolderBtn.addEventListener('click', () => folderInput.click());
    folderInput.addEventListener('change', handleFolderSelection);
    playPauseBtn.addEventListener('click', togglePlayPause);
    prevBtn.addEventListener('click', playPreviousSong);
    nextBtn.addEventListener('click', playNextSong);
    volumeControl.addEventListener('input', updateVolume);
    audioElement.addEventListener('timeupdate', updateProgress);
    audioElement.addEventListener('ended', playAgain);
    audioElement.addEventListener('loadedmetadata', updateDuration);
    progressBar.addEventListener('click', handleProgressEvent);
    document.addEventListener("keydown", onKeyDownEvent)
    document.addEventListener("contextmenu", onMenuShow)
}
// 禁止右鍵
function onMenuShow(event) {
    event.preventDefault()
}

// 处理空格键实现播放/暂停切换
function onKeyDownEvent(event) {
    if (event.keyCode === 32) {  
        togglePlayPause()
        event.preventDefault()
        return false
    }
}

// 处理点击进度条跳转
function handleProgressEvent(event) {
    const width = this.offsetWidth;
    const clickX = event.offsetX;
    seekToLyric((clickX / width) * (audioElement.duration))
}
// 处理文件夹选择
function handleFolderSelection(event) {
    const files = Array.from(event.target.files);

    // 筛选MP3文件和SRT文件
    const mp3Files = files.filter(file => file.name.toLowerCase().endsWith('.mp3'));
    const srtFiles = files.filter(file => file.name.toLowerCase().endsWith('.srt'));

    if (mp3Files.length === 0) {
        alert('未找到MP3文件！');
        return;
    }

    // 创建音频文件列表
    audioFiles = mp3Files.map(mp3File => {
        const baseName = mp3File.name.replace(/\.mp3$/i, '');
        const srtFile = srtFiles.find(srt => srt.name.replace(/\.srt$/i, '') === baseName);

        return {
            name: baseName,
            mp3Path: mp3File.webkitRelativePath || mp3File.name,
            mp3File: mp3File,
            srtFile: srtFile
        };
    });

    // 显示播放器界面
    fileSelector.style.display = 'none';
    sidebar.style.display = 'block';
    mainContent.style.display = 'flex';

    // 填充歌曲列表
    renderSongList();

    // 默认播放第一首歌
    if (audioFiles.length > 0) {
        playSong(0);
    }
}

// 渲染歌曲列表
function renderSongList() {
    songList.innerHTML = '';

    audioFiles.forEach((song, index) => {
        const li = document.createElement('li');
        li.className = 'song-item';
        li.textContent = song.name;
        li.addEventListener('click', () => playSong(index));

        if (index === currentSongIndex) {
            li.classList.add('active');
        }

        songList.appendChild(li);
    });
}

// 播放歌曲
function playSong(index) {
    if (index < 0 || index >= audioFiles.length) return;

    // 停止当前播放
    audioElement.pause();
    clearInterval(updateInterval);

    // 更新当前歌曲索引
    currentSongIndex = index;
    const song = audioFiles[index];

    // 更新UI
    renderSongList();

    // 加载音频
    const audioUrl = URL.createObjectURL(song.mp3File);
    audioElement.src = audioUrl;
    audioElement.load();

    // 加载歌词
    loadLyrics(song.srtFile).then(loadedLyrics => {
        lyrics = loadedLyrics;
        renderLyrics();
    }).catch(() => {
        lyrics = [];
        renderLyrics();
    });

    // 播放
    audioElement.play();
    isPlaying = true;
    playPauseBtn.textContent = '暂停';

    // 开始更新进度
    updateInterval = setInterval(updateLyricsHighlight, 100);
}

// 加载歌词文件
function loadLyrics(srtFile) {
    return new Promise((resolve, reject) => {
        if (!srtFile) {
            reject('No subtitle file');
            return;
        }

        const reader = new FileReader();
        reader.onload = (event) => {
            const srtContent = event.target.result;
            const parsedLyrics = parseSrt(srtContent);
            resolve(parsedLyrics);
        };
        reader.onerror = reject;
        reader.readAsText(srtFile);
    });
}

// 解析SRT文件
function parseSrt(srtContent) {
    const lines = srtContent.split('\n');
    const lyrics = [];
    let currentBlock = null;

    for (const line of lines) {
        if (/^\d+$/.test(line.trim())) {
            // 序号行
            if (currentBlock) lyrics.push(currentBlock);
            currentBlock = { index: parseInt(line.trim()), text: '', startTime: 0, endTime: 0 };
        } else if (line.includes('-->')) {
            // 时间行
            if (!currentBlock) continue;
            const times = line.split('-->').map(t => t.trim());
            currentBlock.startTime = parseSrtTime(times[0]);
            currentBlock.endTime = parseSrtTime(times[1]);
        } else if (line.trim()) {
            // 歌词行
            if (currentBlock) currentBlock.text += line.trim() + '\n';
        }
    }

    if (currentBlock) lyrics.push(currentBlock);
    return lyrics;
}

// 解析SRT时间格式
function parseSrtTime(timeStr) {
    const parts = timeStr.split(':');
    const lastPart = parts[2].split(',');

    const hours = parseInt(parts[0]);
    const minutes = parseInt(parts[1]);
    const seconds = parseInt(lastPart[0]);
    const milliseconds = parseInt(lastPart[1]);

    return hours * 3600 + minutes * 60 + seconds + milliseconds / 1000;
}

// 渲染歌词
function renderLyrics() {
    lyricsContainer.innerHTML = '';

    if (lyrics.length === 0) {
        lyricsContainer.innerHTML = '<p>无可用字幕</p>';
        return;
    }

    lyrics.forEach((lyric, index) => {
        const div = document.createElement('div');
        div.className = 'lyric-line';
        div.textContent = lyric.text.trim();
        div.dataset.startTime = lyric.startTime;
        div.dataset.endTime = lyric.endTime;
        div.addEventListener('click', () => seekToLyric(lyric.startTime));
        lyricsContainer.appendChild(div);
    });
}

// 更新歌词高亮
function updateLyricsHighlight() {
    if (!audioElement || !lyrics.length) return;

    const currentTime = audioElement.currentTime;
    const lyricLines = document.querySelectorAll('.lyric-line');

    lyricLines.forEach(line => {
        line.classList.remove('active');

        const startTime = parseFloat(line.dataset.startTime);
        const endTime = parseFloat(line.dataset.endTime);

        if (currentTime >= startTime && currentTime <= endTime) {
            line.classList.add('active');

            // 自动滚动到当前歌词
            line.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
    });
}

// 跳转到歌词对应时间
function seekToLyric(time) {
    audioElement.currentTime = time;
    if (isPlaying) {
        return
    }
    togglePlayPause()
}

// 切换播放/暂停
function togglePlayPause() {
    if (audioFiles.length === 0) return;

    if (isPlaying) {
        audioElement.pause();
        playPauseBtn.textContent = '播放';
        clearInterval(updateInterval);
    } else {
        if (currentSongIndex === -1) {
            playSong(0);
        } else {
            audioElement.play();
            updateInterval = setInterval(updateLyricsHighlight, 100);
        }
        playPauseBtn.textContent = '暂停';
    }

    isPlaying = !isPlaying;
}

// 播放上一首
function playPreviousSong() {
    if (audioFiles.length === 0) return;

    let newIndex = currentSongIndex - 1;
    if (newIndex < 0) newIndex = audioFiles.length - 1;

    playSong(newIndex);
}

// 播放下一首
function playNextSong() {
    if (audioFiles.length === 0) return;

    let newIndex = currentSongIndex + 1;
    if (newIndex >= audioFiles.length) newIndex = 0;

    playSong(newIndex);
}

// 重播
function playAgain() {
    playSong(currentSongIndex);
}


// 更新进度条
function updateProgress() {
    if (!audioElement.duration) return;

    const progress = (audioElement.currentTime / audioElement.duration) * 100;
    progressBar.value = progress;

    currentTimeDisplay.textContent = formatTime(audioElement.currentTime);
}

// 更新总时长
function updateDuration() {
    durationDisplay.textContent = formatTime(audioElement.duration);
}

// 格式化时间（秒 → MM:SS）
function formatTime(seconds) {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins < 10 ? '0' : ''}${mins}:${secs < 10 ? '0' : ''}${secs}`;
}

// 更新音量
function updateVolume() {
    audioElement.volume = volumeControl.value;
}